﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace Common.Framework.CommonDAL
{
   

    /// <summary>
    ///     业务层所有业务类的基类
    /// </summary>
    public class ServiceAdapter<TDbEntitie>
        where TDbEntitie : DbContext, new()
    {

#if UnitTest       
        private Adapter<DbModelEntities> _adapter;
        /// <summary>
        ///     数据库底层适配器
        /// </summary>
        internal Adapter<DbModelEntities> Adapter
        {
            get
            {
                return _adapter = (_adapter ?? new Adapter<DbModelEntities>());
            }
        }
#else
        /// <summary>
        ///     数据库底层适配器
        /// </summary>
        [Import]
        protected DbAdapter<TDbEntitie> Adapter{get{return new DbAdapter<TDbEntitie>();}}


#endif
        public delegate object ExecuteServiceCallBackHandler();
        /// <summary>
        ///     执行业务方法,建议业务层所有业务均执行该方法
        /// </summary>
        /// <param name="callBackHandler">委托函数</param>
        /// <param name="isOpenTransaction">是否开启事务[批量操作(insert、update、delete)操作请开启事务]</param>
        /// <returns></returns>
        public virtual object ExecuteService(ExecuteServiceCallBackHandler callBackHandler, bool isOpenTransaction = true)
        {
            object ret = null;
            if (isOpenTransaction)
            {
                using (var ts = new TransactionScope())
                {
                    if (callBackHandler != null)
                        ret = callBackHandler();
                    ts.Complete();
                }
            }
            else
            {
                ret = callBackHandler();
            }
            return ret;
        }



        /// <summary>
        /// 创建通用的数据库操作对象
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="dbProviderType">数据库驱动类型</param>
        /// <param name="isTran">是否开启事务执行</param>
        /// <returns></returns>
        public virtual DbHelper CreateDbHelper(string connectionString, DbHelper.DbProviderType dbProviderType, bool isTran = false)
        {
            return new DbHelper(connectionString, dbProviderType, isTran);
        }
    }
}
